package com.kye.express.business.jpush;


import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import com.google.gson.Gson;
import com.kye.express.BuildConfig;
import com.kye.express.R;
import com.kye.express.business.splash.SplashActivity;
import com.kye.express.utils.StringUtils;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.bean.jpush.PushSplashModel;

import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;

public class JpushNotificationUtils {
    private static final String SP_KEY_PUSH_MODEL = "pushSplashBean";

    private NotificationManager mNotifyManager;
    private Notification mNotification;
    private PendingIntent mPendingIntent;// 显示通知栏具体信息
    private Context mContext;


    public JpushNotificationUtils(Context context) {
        mContext = context;
        mNotifyManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
    }

    /**
     * 判断app是否启动
     *
     * @param context
     * @return
     */
    public static boolean checkApkExist(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(BuildConfig.APPLICATION_ID) &&
                    info.baseActivity.getPackageName().equals(BuildConfig.APPLICATION_ID)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断当前应用程序处于前台还是后台
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测是否有未处理的jpush消息，如果有就处理
     */
    public static void checkNeedHandleJpushMessage(Activity activity) {
        if (!activity.getClass().getName().equals(SplashActivity.class.getName())) {
            PushSplashModel pushSplashBean = getPushSplashBean();
            if (pushSplashBean != null) {
                JPushResponseParseHelper.getInstance().init(activity, pushSplashBean).startParseJPushResponse();
            }
        }
    }

    /**
     * 缓存 激光推送消息
     *
     * @param pushSplashBean
     */
    public static void savePushSplashBean(PushSplashModel pushSplashBean) {
        if (pushSplashBean == null) {
            SharedPreferencesManager.commit(SP_KEY_PUSH_MODEL, "");
            return;
        }
        try {
            Gson gson = new Gson();
            String jsonStr = gson.toJson(pushSplashBean);
            SharedPreferencesManager.commit(SP_KEY_PUSH_MODEL, jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 激光推送缓存消息
     *
     * @return
     */
    public static PushSplashModel getPushSplashBean() {
        PushSplashModel pushSplashBean = null;
        String jsonStr = SharedPreferencesManager.get(SP_KEY_PUSH_MODEL);
        if (StringUtils.isNullOrEmpty(jsonStr)) {
            return null;
        }
        try {
            Gson gson = new Gson();
            pushSplashBean = gson.fromJson(jsonStr, PushSplashModel.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pushSplashBean;
    }


    /**
     * 发送通知
     *
     * @param pushSplashBean
     */
    public void sendJpushBrodcastPendingIntent(PushSplashModel pushSplashBean) {

        Intent mIntent = new Intent(mContext, JpushNotificationClickReceiver.class);
        mIntent.putExtra(JpushNotificationClickReceiver.ARG_DATA, pushSplashBean);
        mPendingIntent = PendingIntent.getBroadcast(mContext, pushSplashBean.getPushId(), mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mNotification = new Notification.Builder(mContext)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(pushSplashBean.getTitle())
                    .setContentText(pushSplashBean.getContent())
                    .setWhen(0).build();
        } else {
            mNotification = new Notification();
            mNotification.icon = R.mipmap.ic_launcher;
            mNotification.tickerText = pushSplashBean.getTitle();
            mNotification.when = 0;
            Notification.Builder builder = new Notification.Builder(mContext)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(pushSplashBean.getTitle())
                    .setContentText(pushSplashBean.getContent())
                    .setWhen(System.currentTimeMillis());
            mNotification = builder.getNotification();
        }
        if (mPendingIntent != null) {
            mNotification.contentIntent = mPendingIntent;
        }
        mNotification.flags |= Notification.FLAG_AUTO_CANCEL; // 点击清除按钮或点击通知后会自动消失
        mNotification.defaults = Notification.DEFAULT_SOUND; // 调用系统自带声音
        mNotifyManager.notify(pushSplashBean.getPushId(), mNotification);
    }

    public void removeNotifyById(int id) {
        mNotifyManager.cancel(id);
    }

}
